#pragma once
#include <iostream>
#include "common.hpp"
#include <string>
#include <sys/shm.h>
#include <fcntl.h>

const int gsize = 1024;
const int progid = 0x66;
const int gmode = 0666;
const int gdefaultid = -1;
const std::string pathname = ".";
#define CREATER "creater"
#define USER "user"

class Shm
{
private:
    void CreateHelper(int shmflg)
    {
        printf("key: 0x%x\n", _key);
        _shmid = shmget(_key, _size, shmflg);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        else
        {
            printf("shmid: %d\n", _shmid);
        }
    }

    // 创建的一定要是一个全新的共享内存
    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | gmode);
    }

    void Get()
    {
        CreateHelper(IPC_CREAT);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat");
        }
        else
        {
            std::cout << "attach sucess" << std::endl;
        }
    }

    void Detach()
    {
        int n = shmdt(_start_mem);
        if (n < 0)
        {
            ERR_EXIT("shmdt");
        }
        else
        {
            std::cout << "detach sucess" << std::endl;
        }
    }

    void Destory()
    {
        if (_shmid == gdefaultid)
            return;
        Detach();
        if (_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n < 0)
            {
                ERR_EXIT("shmctl");
            }
            else
            {
                printf("shmctl delete shm: %d success!\n", _shmid);
            }
        }
    }

public:
    Shm(const std::string &pathname, const int progid, const std::string &usertype)
        : _shmid(gdefaultid),
          _usertype(usertype),
          _size(gsize),
          _start_mem(nullptr)

    {
        _key = ftok(pathname.c_str(), progid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        else
        {
            std::cout << "ftok success" << std::endl;
        }
        if(_usertype==CREATER)
        {
            Create();
        }
        else 
        {
            Get();
        }
        Attach();
    }
    ~Shm()
    {
        Destory();
    }
    void *VirtualAddr()
    {
        return _start_mem;
    }

    int Size()
    {
        return _size;
    }
    void Attr()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid, IPC_STAT, &ds); // ds:输出型参数
        printf("shm_segsz: %ld\n", ds.shm_segsz);
        printf("key: 0x%x\n", ds.shm_perm.__key);
    }

private:
    key_t _key;
    int _shmid;
    std::string _usertype;
    int _size;
    void *_start_mem;
};